package com.cheche.dn.domain.admin;

import com.cheche.dn.Result;
import com.cheche.dn.common.base.Service;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * Created by cheshun on 15/8/28.
 */
@org.springframework.stereotype.Service
public class RoleService {

    @Autowired
    private Service service;

    public Result delete(Long... ids) {
        if (ids != null) {
            for (Long id : ids) {
                Role role = service.find(Role.class, id);
                if (role == null) {
                    return Result.error(String.format("Role is not exist for id %s", id.toString()));
                }
                if (role.getIsSystem()) {
                    return Result.error("Built-in permission system can not be deleted");
                }
                if (role.getAdmins() != null && !role.getAdmins().isEmpty()) {
                    return Result.error("Associated by the admins");
                }
            }
            service.delete(Role.class, ids);
        }
        return Result.success();
    }

    public Set<Authority> findAuthoritySet(Long... authorityIds) {
        Set<Authority> authorities = Sets.newHashSet();
        List<Authority> authorityList = service.findList(Authority.class, authorityIds);
        authorities.addAll(authorityList);
        return authorities;
    }
}
